<template>
  <div class="app-container">
    <el-card class="box-card" :body-style="{ padding: '10px' }">
      <el-form :inline="true" size="mini">
        <el-form-item>
          <el-input
            v-model="listQuery.name"
            placeholder="请输入内容"
            clearable
            @keyup.enter.native="handleFilter"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click.native="handleFilter"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            :disabled="selections.length === 0"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="users"
        border
        v-loading="listLoading"
        fit
        highlight-current-row
        style="width: 100%"
        size="mini"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align ? column.align : ''"
          :width="column.width ? column.width : ''"
        >
          <!-- <template slot-scope="scope">
            <div v-if="column.key == 'status_name'">
              <el-tag
                v-if="scope.row['status'] === 0"
                size="small"
                type="danger"
                >{{ scope.row.status_name }}</el-tag
              >
              <el-tag
                v-else-if="scope.row['status'] === 1"
                size="small"
                type="success"
                >{{ scope.row.status_name }}</el-tag
              >
            </div>
            <div v-else>
              {{ scope.row[column.key] }}
            </div>
          </template> -->
        </el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getVideoUserList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="40%">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="padding: 0 30px"
        status-icon
        size="small"
      >
        <el-form-item label="微信ID" prop="openid">
          <el-input
            v-model="form.openid"
            placeholder="微信ID"
            clearable
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="姓名" clearable />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="昵称" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="telephone">
          <el-input v-model="form.telephone" placeholder="手机号" clearable />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="性别">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="2"></el-option>
            <el-option label="未知" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-input v-model="form.role_id" placeholder="角色" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="mini" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="mini" @click="handleSave(false)"
          >保存</el-button
        >
        <el-button
          type="primary"
          size="mini"
          v-if="dialogType == 'new'"
          @click="handleSave(true)"
          >保存并新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getVideoUsers,
  addVideoUser,
  updateVideoUser,
  deleteVideoUser,
  delVideoUsers,
} from "@/api/rooms";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: undefined,
  openid: "",
  nickname: "",
  name: "",
  telephone: "",
  sex: "",
  headimgurl: "",
  role_id: null,
};

export default {
  name: "VideoUser",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        openid: [
          {
            type: "string",
            required: true,
            message: "请输入用户id",
            trigger: "blur",
          },
        ],
      },
      tableColumns: [
        {
          key: "openid",
          title: "用户微信ID",
          align: "left",
        },
        {
          key: "name",
          title: "姓名",
          align: "left",
        },
        {
          key: "nickname",
          title: "昵称",
          align: "left",
        },
        {
          key: "telephone",
          title: "手机号",
          width: "120px",
          align: "left",
        },
        {
          key: "sex_name",
          title: "性别",
          width: "120px",
          align: "center",
        },
      ],
      title: "视频客户",
      dialogVisible: false,
      dialogType: "new",
      users: [],
      selections: [],

      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 10,
        name: undefined,
      },
    };
  },
  computed: {
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getVideoUserList();
  },
  methods: {
    getVideoUserList() {
      this.listLoading = true;
      getVideoUsers(this.listQuery)
        .then((res) => {
          this.users = res.results;
          this.listLoading = false;
          this.total = res.count;
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("获取用户列表失败!");
          this.listLoading = false;
        });
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getVideoUserList();
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },

    // 增加f
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该运营商吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteVideoUser(row.id);
          this.getVideoUserList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    handleBatchDelete() {
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delVideoUsers(sel_ids);

          this.getVideoUserList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";

        let res = null;

        if (isEdit) {
          res = await updateVideoUser(this.form);
        } else {
          res = await addVideoUser(this.form);
        }

        this.getVideoUserList();

        const { openid, name, nickname } = res;
        if (flag) {
          this.form = Object.assign({}, defaultForm);
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>微信ID: ${openid}</div>
              <div>姓名: ${name}</div>
              <div>昵称: ${nickname}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
// .el-table {
//   margin-top: 10px;
//   width: 100%;
// }
</style>